package com.treasure.hunt.hunt

import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import androidx.annotation.RawRes
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.integration.webp.decoder.WebpDrawable
import com.bumptech.glide.integration.webp.decoder.WebpDrawableTransformation
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.Transformation
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.module.lemlin.base.loadRoundImage
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.module.lemlin.util.AnimManager
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.entity.Action
import com.treasure.hunt.entity.MainBean
import com.treasure.hunt.mine.MineConfigActivity
import com.treasure.hunt.mode.HuntViewMode
import com.treasure.hunt.popup.DialogFlopPopup
import kotlinx.android.synthetic.main.fragment_hunt_grade.*
import org.greenrobot.eventbus.EventBus
import razerdp.basepopup.BasePopupWindow

class HuntGradeFragment : ViewModeFragment<HuntViewMode>() {

    companion object {
        private const val EXTRA_NAME_TYPE = "EXTRA_NAME_CATEGORY"
        fun newInstance(type: Int): HuntGradeFragment {
            val bundle: Bundle = Bundle().apply {
                putInt(EXTRA_NAME_TYPE, type)
            }
            return HuntGradeFragment().apply {
                arguments = bundle
            }
        }
    }

    private val flopPopup: DialogFlopPopup by lazy {
        DialogFlopPopup(context = requireContext(), onAnimationEnd = {
            if (it.drawable == null)
                return@DialogFlopPopup

            val mainBean: MainBean<Action, Any> = MainBean(
                type = Action.GO_MINE
            )
            EventBus.getDefault().post(mainBean)

            val circleImageView = ImageView(activity)
            val layoutParams = LinearLayout.LayoutParams(
                ConvertUtils.dp2px(50f), ConvertUtils.dp2px(50f)
            )
            circleImageView.layoutParams = layoutParams
            circleImageView.loadRoundImage(it.drawable,radius = 25)

            val animManager: AnimManager = AnimManager.Builder()
                .with(requireActivity())
                .animModule(AnimManager.AnimModule.BIG_CIRCLE)
                .time(1500)
                .listener(object : AnimManager.AnimListener {
                    override fun setAnimBegin(a: AnimManager) {}
                    override fun setAnimEnd(a: AnimManager) {
                        a.stopAnim()
                    }
                })
                .animView(circleImageView)
                .build()
            animManager.startAnim(
                intArrayOf(
                    (ScreenUtils.getAppScreenWidth() / 2) - ConvertUtils.dp2px(25f),
                    ScreenUtils.getAppScreenHeight() / 2
                ), intArrayOf(
                    ScreenUtils.getAppScreenWidth() / 8 * 7,
                    ScreenUtils.getAppScreenHeight()
                )
            )
        })
    }

    override val layoutResId: Int
        get() = R.layout.fragment_hunt_grade

    override fun viewModel(): HuntViewMode {
        return createViewModel()
    }

    override fun initView() {

        ivHuntGradeHelp.setOnClickListener {
            arguments?.getInt(EXTRA_NAME_TYPE)?.let {
                if (it == 1) {
                    MineConfigActivity.open(
                        activity = requireActivity(),
                        title = "普通寻宝规则",
                        name = "ordinary_video_rule"
                    )
                }
                if (it == 2) {
                    MineConfigActivity.open(
                        activity = requireActivity(),
                        title = "豪华寻宝规则",
                        name = "luxury_video_rule"
                    )
                }
            }
        }

        tvHuntGradeGetNum.setOnClickListener {
            arguments?.getInt(EXTRA_NAME_TYPE)?.let {
                if (it == 2) {
                    val mainBean: MainBean<Action, Any> = MainBean(
                        type = Action.GO_TASK
                    )
                    EventBus.getDefault().post(mainBean)
                } else {
                    val maps: MutableMap<String, Any?> = mutableMapOf(
                        "advertisement_type" to 5,
                        "luck_draw_type" to it
                    )
                    viewModel.videoType(maps)
                }
            }

        }

        tvHuntGradeOpenBox.setOnClickListener {
            arguments?.getInt(EXTRA_NAME_TYPE)?.let {
                if (viewModel.luckyNumLiveData.value?.httpData?.data?.num == 0) {
                    toast("开宝箱次数不够！")
                    return@setOnClickListener
                }
                if (it == 1) {
                    fillBoxImage(R.drawable.ic_0002)
                }
                if (it == 2) {
                    fillBoxImage(R.drawable.ic_0001)
                }
                viewModel.luckyChest(it)
                tvHuntGradeOpenBox.isEnabled = false
                tvHuntGradeGetNum.isEnabled = false
            }
        }


        arguments?.getInt(EXTRA_NAME_TYPE)?.let {
            if (it == 1) {
                ivHuntGradeBox2.setImageResource(R.mipmap.ic_21903)
            }
            if (it == 2) {
                ivHuntGradeBox2.setImageResource(R.mipmap.ic_21902)
            }
        }

        flopPopup.setOnDismissListener(object : BasePopupWindow.OnDismissListener() {
            override fun onDismiss() {
                ivHuntGradeBox2.visibility = View.VISIBLE
            }
        })

    }

    override fun initData() {
        val type: Int = arguments?.getInt(EXTRA_NAME_TYPE)
            ?: return
        viewModel.luckyGetLuckDraw(type)
    }

    override fun onRefreshLoad() {
        super.onRefreshLoad()
        val type: Int = arguments?.getInt(EXTRA_NAME_TYPE)
            ?: return
        viewModel.luckyGetLuckDraw(type)
//        ivHuntGradeBox2.visibility = View.VISIBLE
    }

    override fun initViewMode() {
        viewModel.luckyNumLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                tvHuntGradeRemainNum.text = "剩余次数：${it.num}"
            }
        })

        viewModel.videoTypeLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
                ?: return@Observer
            val codeId: String? = response.httpData?.data?.advertising_space
            if (codeId == null) {
                toast("广告位ID为空")
            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdCSJ(mActivity = requireActivity(), codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdYLH(mActivity = requireActivity(), codeId = codeId)
            }
        })

        viewModel.videoEndLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                flopPopup.fillData(it.data).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
                initData()
            }
        })

        viewModel.videoNoRewardLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
            val codeId: String? = response.httpData?.data?.advertising_space
            if (cid == null) {

            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdCSJ(mActivity = requireActivity(),codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdYLH(mActivity = requireActivity(),codeId = codeId)
            }
        })

        viewModel.luckyGiftLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知错误")
                ivHuntGradeBox2.visibility = View.VISIBLE
                tvHuntGradeOpenBox.isEnabled = true
                tvHuntGradeGetNum.isEnabled = true
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            tvHuntGradeOpenBox.isEnabled = true
            tvHuntGradeGetNum.isEnabled = true
            arguments?.getInt(EXTRA_NAME_TYPE)?.let {
                viewModel.luckyGetLuckDraw(it)
            }
            response.httpData?.data?.let {
                flopPopup.fillData(it).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
            }
        })

//        viewModel.videoNoRewardLiveData.observe(this as LifecycleOwner, Observer { response ->
//            if (response.status != Status.SUCCESS)
//                return@Observer
//            val cid: Int? = response.httpData?.data?.cid
//            if (cid == null) {
//
//            } else if (cid == 1) {
//                viewModel.loadNativeExpressAdCSJ(requireActivity())
//            }
//        })


        viewModel.rewardVerifyAdLiveData.observe(
            this as LifecycleOwner,
            Observer { isRewardVerify ->
                if (!isRewardVerify)
                    return@Observer
                viewModel.videoTypeLiveData.value?.httpData?.data?.let {
                    viewModel.videoEnd(it.video_log_id)
                }
            })

        viewModel.viewAdLiveData.observe(viewLifecycleOwner, Observer { view ->
            view?.let {
                flopPopup.fillViewAd(view)
            }
        })

    }

    private fun fillBoxImage(@RawRes @DrawableRes iconRes: Int) {

        ivHuntGradeBox2.visibility = View.INVISIBLE
        ivHuntGradeBox.visibility = View.VISIBLE
        val circleCrop: Transformation<Bitmap> = CircleCrop()
        Glide.with(requireContext()).load(iconRes)
            .addListener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?, model: Any?,
                    target: Target<Drawable>?, isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?, model: Any?, target: Target<Drawable>?,
                    dataSource: DataSource?, isFirstResource: Boolean
                ): Boolean {
                    (resource as? WebpDrawable)?.loopCount = 1
                    return false
                }
            })
            .optionalTransform(circleCrop)
            .optionalTransform<WebpDrawable>(
                WebpDrawable::class.java, WebpDrawableTransformation(circleCrop)
            ).into(ivHuntGradeBox)
    }

}